//
//  XMAddFriendViewController.m
//  XMJJ_zml
//
//  Created by apple on 2025/5/12.
//

#import "XMAddFriendViewController.h"
#import "XMAddFriendView.h"
#import "XMNetwork+mine.h"
#import "XMFriendModel.h"
#import <AddressBook/AddressBook.h>
#import <Contacts/Contacts.h>
#import "XMAddressBookViewController.h"
#import "XMScanCodeViewController.h"

@interface XMAddFriendViewController ()<XMAddFriendViewDelegate>

@property (nonatomic, strong) XMAddFriendView *addFriendView;

@end

@implementation XMAddFriendViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hideNavigationBar:YES animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatUI];
}

- (void)creatUI {
    [self.view addSubview:self.addFriendView];
    [self getRecommendFriend];
}

//推荐朋友
- (void)getRecommendFriend {
    XMWeakSelf;
    [_Network getRecommendFriendList:^(id  _Nonnull responseObject) {
        NSArray *friendModelArr = [NSArray yy_modelArrayWithClass:[XMFriendModel class] json:responseObject[@"data"]];
        [weakSelf.addFriendView setContentWithReFriendModelArr:friendModelArr isSearch:NO];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//搜索朋友
- (void)searchWithSearchKey:(NSString *)searchKey {
    XMWeakSelf;
    [_Network getSearchFriendListWithSearchKey:searchKey
                                       success:^(id  _Nonnull responseObject) {
        NSArray *friendModelArr = [NSArray yy_modelArrayWithClass:[XMFriendModel class] json:responseObject[@"data"]];
        [weakSelf.addFriendView setContentWithReFriendModelArr:friendModelArr isSearch:YES];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//关注朋友
- (void)attentionFriendWithUserId:(NSString *)userId {
    XMWeakSelf;
    [_Network friendAttentionWithUserId:userId success:^(id  _Nonnull responseObject) {
        [weakSelf.addFriendView attentionSuccess];
    } failure:^(NSError * _Nonnull error) {
        
    }];;
}

//取消关注朋友
- (void)cancelAttentionFriendWithUserId:(NSString *)userId {
    XMWeakSelf;
    [_Network cancelAttentionWithUserId:userId
                                success:^(id  _Nonnull responseObject) {
        [weakSelf.addFriendView attentionSuccess];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//获取通讯录好友
- (void)getAddressBookInfoWithUserList:(NSArray *)userInfoArr {
    XMWeakSelf;
    [_Network getAddressBookWithUserList:userInfoArr
                                 success:^(id  _Nonnull responseObject) {
        NSArray *friendModelArr = [NSArray yy_modelArrayWithClass:[XMFriendModel class] json:responseObject[@"data"]];
        XMAddressBookViewController *addressBookVC = [[XMAddressBookViewController alloc] init];
        addressBookVC.userModelArr = friendModelArr;
        [weakSelf.navigationController pushViewController:addressBookVC animated:YES];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - Delegate
- (void)searchFriendWithSearchKey:(NSString *)searchKey {
    [self searchWithSearchKey:searchKey];
}

- (void)friendAttentionWithUserId:(NSString *)userId status:(nonnull NSString *)statusStr {
    if (statusStr.length > 0 && [statusStr isEqualToString:@"1"]) {
        [self cancelAttentionFriendWithUserId:userId];
    }
    else {
        [self attentionFriendWithUserId:userId];
    }
}

- (void)addFriendFromThirdParty:(NSInteger)thirdParty {
    switch (thirdParty) {
        case 0: {
            CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
            if (status == CNAuthorizationStatusNotDetermined) {
                CNContactStore *store = [[CNContactStore alloc] init];
                    [store requestAccessForEntityType:CNEntityTypeContacts
                                completionHandler:^(BOOL granted, NSError * _Nullable error) {
                    if (granted) {
                        [self getAddressBook];
                    }
                    else {
                        
                    }
                }];
            }
            else if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusRestricted) {
//                [self getAddressBook];
            }
            else {
                [self getAddressBook];
            }
        }
            break;
        case 1: {
            
        }
            break;
        case 2: {
            XMScanCodeViewController *scanCodeVC = [[XMScanCodeViewController alloc] init];
            [self.navigationController pushViewController:scanCodeVC animated:YES];
        }
            break;
            
        default:
            break;
    }
}

- (void)getAddressBook {
    CNContactStore *store = [[CNContactStore alloc] init];
    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[CNContactPhoneNumbersKey, CNContactFamilyNameKey, CNContactGivenNameKey]];
    
    NSMutableArray *contactsArr = [NSMutableArray array];
    [store enumerateContactsWithFetchRequest:request
                                       error:nil
                                  usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        NSLog(@"%@%@", contact.familyName, contact.givenName);
        
        for (int i = 0; i < contact.phoneNumbers.count; i ++) {
            CNPhoneNumber *phoneNum = (contact.phoneNumbers[i]).value;
            NSMutableDictionary *userDic = [NSMutableDictionary dictionary];
            NSLog(@"%@", phoneNum.stringValue);
            NSString *phoneNumStr = [phoneNum.stringValue stringByReplacingOccurrencesOfString:@"）" withString:@""];
            phoneNumStr = [phoneNumStr stringByReplacingOccurrencesOfString:@"（" withString:@""];
            phoneNumStr = [phoneNumStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
            phoneNumStr = [phoneNumStr stringByReplacingOccurrencesOfString:@")" withString:@""];
            phoneNumStr = [phoneNumStr stringByReplacingOccurrencesOfString:@"(" withString:@""];
            phoneNumStr = [phoneNumStr stringByReplacingOccurrencesOfString:@" " withString:@""];
            [userDic safe_setObject:[NSString stringWithFormat:@"%@%@", contact.familyName, contact.givenName] forKey:@"name"];
            [userDic safe_setObject:phoneNumStr forKey:@"phone"];
            [contactsArr addObject:userDic];
        }
//                    name  phone
    }];
    [self getAddressBookInfoWithUserList:contactsArr];
}

#pragma mark - Init
- (XMAddFriendView *)addFriendView {
    if (!_addFriendView) {
        _addFriendView = [[XMAddFriendView alloc] initWithFrame:self.view.bounds];
        _addFriendView.delegate = self;
    }
    return _addFriendView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
